SpringBoot调用http请求的6种方式
场景:基于Spring Boot使用Java调用http请求的6种方式。服务端发布一个POST请求和2个GET请求。使用6种方式实现的客户端都调用服务端发布的这3个方法。可以直观感受和比对6种http请求的客户端。
版本:
1 | Spring Boot 2.6.3 |
案例场景
本例实现6种方式客户端调用同一个服务端的3种方法。
服务端
在服务端发布一个POST请求,2个GET请求。
接口信息
POST请求
1 | [访问URL]: http://127.0.0.1:19091/server/comm/f1 |
GET请求(一)
1 | [访问URL]: http://127.0.0.1:19091/server/comm/f2 |
GET请求(二)
1 | [访问URL]: http://127.0.0.1:19091/server/comm/f3/{obj} |
Java调用http请求的6种方式
HttpURLConnection调用http请求
Jar包位置
HttpURLConnection,全称:java.net.HttpURLConnection。
JDK 1.8中自带的rt.jar包中的java.net包内的类。客户端代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99public class Utils01JdkClient {
public static void main(String[] args) throws Exception {
f1();
f2();
f3();
}
/**
* 1.使用HttpURLConnection调用服务端的POST请求
* 服务端入参注解: @RequestBody
*/
public static void f1() throws Exception {
// 1.请求URL
String postUrl = "http://127.0.0.1:19091/server/comm/f1";
// 2.请求参数JSON格式
Map<String, String> map = new HashMap<>();
map.put("userName", "HangZhou20220718");
map.put("tradeName", "Vue进阶教程");
String json = JSON.toJSONString(map);
// 3.创建连接与设置连接参数
URL urlObj = new URL(postUrl);
HttpURLConnection httpConn = (HttpURLConnection) urlObj.openConnection();
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Charset", "UTF-8");
// POST请求且JSON数据,必须设置
httpConn.setRequestProperty("Content-Type", "application/json");
// 打开输出流,默认是false
httpConn.setDoOutput(true);
// 打开输入流,默认是true,可省略
httpConn.setDoInput(true);
// 4.从HttpURLConnection获取输出流和写数据
OutputStream oStream = httpConn.getOutputStream();
oStream.write(json.getBytes());
oStream.flush();
// 5.发起http调用(getInputStream触发http请求)
if (httpConn.getResponseCode() != 200) {
throw new Exception("调用服务端异常.");
}
// 6.从HttpURLConnection获取输入流和读数据
BufferedReader br = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
String resultData = br.readLine();
System.out.println("从服务端返回结果: " + resultData);
// 7.关闭HttpURLConnection连接
httpConn.disconnect();
}
/**
* 2.使用HttpURLConnection调用服务端的GET请求
* 服务端入参注解: @RequestParam
*/
public static void f2() throws Exception {
// 1.请求URL与组装请求参数
String getUrl = "http://127.0.0.1:19091/server/comm/f2";
String obj = "Vue进阶教程";
String para = "?obj=" + URLEncoder.encode(obj, "UTF-8");
getUrl = getUrl + para;
// 2.创建连接与设置连接参数
URL urlObj = new URL(getUrl);
HttpURLConnection httpConn = (HttpURLConnection) urlObj.openConnection();
httpConn.setRequestMethod("GET");
httpConn.setRequestProperty("Charset", "UTF-8");
// 3.发起http调用(getInputStream触发http请求)
if (httpConn.getResponseCode() != 200) {
throw new Exception("调用服务端异常.");
}
// 4.从HttpURLConnection获取输入流和读数据
BufferedReader br = new BufferedReader(
new InputStreamReader(httpConn.getInputStream()));
String resultData = br.readLine();
System.out.println("从服务端返回结果: " + resultData);
// 5.关闭HttpURLConnection连接
httpConn.disconnect();
}
/**
* 3.使用HttpURLConnection调用服务端的GET请求
* 服务端入参注解: @PathVariable
*/
public static void f3() throws Exception {
// 1.请求URL与组装请求参数
String getUrl = "http://127.0.0.1:19091/server/comm/f3/";
String obj = "Vue进阶教程";
obj = URLEncoder.encode(obj, "UTF-8");
getUrl = getUrl + obj;
URL urlObj = new URL(getUrl);
// 2.创建连接与设置连接参数
HttpURLConnection httpConn = (HttpURLConnection) urlObj.openConnection();
httpConn.setRequestMethod("GET");
httpConn.setRequestProperty("charset", "UTF-8");
// 3.发起http调用(getInputStream触发http请求)
if (httpConn.getResponseCode() != 200) {
throw new Exception("调用服务端异常.");
}
// 4.从HttpURLConnection获取输入流和读数据
BufferedReader br = new BufferedReader(
new InputStreamReader(httpConn.getInputStream()));
String resultData = br.readLine();
System.out.println("从服务端返回结果: " + resultData);
// 5.关闭HttpURLConnection连接
httpConn.disconnect();
}
}
commons-httpclient调用http请求
- Jar包位置
commons-httpclient,比较早的Jar包,在MVNRepository仓库中,查看的最新维护时间是:2007年8月。1
2
3
4
5<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency> - 客户端代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95public class Utils02CommonsHttpClient {
public static void main(String[] args) throws Exception {
f1();
f2();
f3();
}
/**
* 1.使用commons-httpclient调用服务端的POST请求
* 服务端入参注解: @RequestBody
*/
public static void f1() throws Exception {
// 1.请求URL
String postUrl = "http://127.0.0.1:19091/server/comm/f1";
// 2.请求参数
Map<String, String> map = new HashMap<>();
map.put("userName", "HangZhou20220718");
map.put("tradeName", "Vue进阶教程");
String json = JSON.toJSONString(map);
// 3.创建连接与设置连接参数
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(postUrl);
postMethod.addRequestHeader("Content-Type", "application/json");
RequestEntity entity = new StringRequestEntity(json, "application/json", "UTF-8");
postMethod.setRequestEntity(entity);
//解决返回值中文乱码
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
String resultData = "";
// 4.发起请求
int code = httpClient.executeMethod(postMethod);
if (code != 200) {
throw new Exception("调用服务端异常.");
}
// 5.接收返回值
resultData = postMethod.getResponseBodyAsString();
System.out.println("从服务端返回结果: " + resultData);
// 6.关闭连接
postMethod.releaseConnection();
}
/**
* 2.使用commons-httpclient调用服务端的GET请求
* 服务端入参注解: @RequestParam
*/
public static void f2() throws Exception {
// 1.请求URL与组装请求参数
String getUrl = "http://127.0.0.1:19091/server/comm/f2";
String obj = "Vue进阶教程";
//入参有中文需要编码
String para = "?obj=" + URLEncoder.encode(obj, "UTF-8");
getUrl = getUrl + para;
// 2.创建连接与设置连接参数
HttpClient httpClient = new HttpClient();
GetMethod getMethod = new GetMethod(getUrl);
//解决返回值中文乱码
getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
// 3.发起请求
int code = httpClient.executeMethod(getMethod);
String resultData = "";
if (code != 200) {
throw new Exception("调用服务端异常.");
}
// 4.接收返回值
resultData = getMethod.getResponseBodyAsString();
System.out.println("从服务端返回结果: " + resultData);
// 5.关闭连接
getMethod.releaseConnection();
}
/**
* 3.使用commons-httpclient调用服务端的GET请求
* 服务端入参注解: @PathVariable
*/
public static void f3() throws Exception {
// 1.请求URL与组装请求参数
String getUrl = "http://127.0.0.1:19091/server/comm/f3/";
String obj = "Vue进阶教程";
//入参有中文需要编码
obj = URLEncoder.encode(obj, "UTF-8");
getUrl = getUrl + obj;
// 2.创建连接与设置连接参数
HttpClient httpClient = new HttpClient();
GetMethod getMethod = new GetMethod(getUrl);
//解决返回值中文乱码
getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
// 3.发起请求
int code = httpClient.executeMethod(getMethod);
String resultData = "";
if (code != 200) {
throw new Exception("调用服务端异常.");
}
// 4.接收返回值
resultData = getMethod.getResponseBodyAsString();
System.out.println("从服务端返回结果: " + resultData);
// 5.关闭连接
getMethod.releaseConnection();
}
}
使用org.apache.httpcomponents调用http请求
- Jar包位置
httpcomponents,在MVNRepository仓库中,查看的最新维护时间是:2020年10月。1
2
3
4
5<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency> - 客户端代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87public class Utils03HttpComponentsClient {
public static void main(String[] args) throws Exception {
f1();
f2();
f3();
}
/**
* 1.使用org.apache.httpcomponents调用服务端的POST请求
* 服务端入参注解: @RequestBody
*/
public static void f1() throws Exception {
// 1.请求URL
String postUrl = "http://127.0.0.1:19091/server/comm/f1";
// 2.请求参数
Map<String, String> map = new HashMap<>();
map.put("userName", "HangZhou20220718");
map.put("tradeName", "Vue进阶教程");
String json = JSON.toJSONString(map);
// 3.创建连接与设置连接参数
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(postUrl);
StringEntity entity = new StringEntity(json);
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
// 4.发起请求与接收返回值
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() != 200) {
throw new Exception("调用服务端异常.");
}
HttpEntity res = response.getEntity();
String resultData = EntityUtils.toString(res);
System.out.println("从服务端返回结果: " + resultData);
// 5.关闭连接
httpClient.close();
}
/**
* 2.使用org.apache.httpcomponents调用服务端的GET请求
* 服务端入参注解: @RequestParam
*/
public static void f2() throws Exception {
// 1.请求URL与组装请求参数
String getUrl = "http://127.0.0.1:19091/server/comm/f2";
String obj = "Vue进阶教程";
String para = "?obj=" + URLEncoder.encode(obj, "UTF-8");
getUrl = getUrl + para;
// 2.创建连接与设置连接参数
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(getUrl);
// 3.发起请求与接收返回值
HttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() != 200) {
throw new Exception("调用服务端异常.");
}
HttpEntity res = response.getEntity();
String resultData = EntityUtils.toString(res);
System.out.println("从服务端返回结果: " + resultData);
// 4.关闭连接
httpClient.close();
}
/**
* 3.使用org.apache.httpcomponents调用服务端的GET请求
* 服务端入参注解: @PathVariable
*/
public static void f3() throws Exception {
// 1.请求URL与组装请求参数
String getUrl = "http://127.0.0.1:19091/server/comm/f3/";
String obj = "Vue进阶教程";
//入参有中文需要编码
obj = URLEncoder.encode(obj, "UTF-8");
getUrl = getUrl + obj;
// 2.创建连接与设置连接参数
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(getUrl);
// 3.发起请求与接收返回值
HttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() != 200) {
throw new Exception("调用服务端异常.");
}
HttpEntity res = response.getEntity();
String resultData = EntityUtils.toString(res);
System.out.println("从服务端返回结果: " + resultData);
// 4.关闭连接
httpClient.close();
}
}
使用OkHttp调用http请求
- Jar包位置
com.squareup.okhttp3,本例使用版本。1
2
3
4
5
6
7
8
9
10
11<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.10.0</version>
<exclusions>
<exclusion>
<groupId>com.google.android</groupId>
<artifactId>android</artifactId>
</exclusion>
</exclusions>
</dependency> - 客户端代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
public class Utils04OkHttpClient {
public static void main(String[] args) throws Exception {
f1();
f2();
f3();
}
/**
* 1.使用okhttp调用服务端的POST请求
* 服务端入参注解: @RequestBody
* */
public static void f1() throws Exception {
// 1.请求URL
String postUrl = "http://127.0.0.1:19091/server/comm/f1";
// 2.请求参数
Map<String, String> map = new HashMap<>();
map.put("userName", "HangZhou20220718");
map.put("tradeName", "Vue进阶教程");
String json = JSON.toJSONString(map);
// 3.创建连接与设置连接参数
MediaType mediaType = MediaType.parse("application/json; charset=UTF-8");
RequestBody requestBody = RequestBody.Companion.create(json, mediaType);
Request request = new Request.Builder().url(postUrl).post(requestBody).build();
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
// 4.发起请求与接收返回值
Response response = okHttpClient.newCall(request).execute();
String resultData = response.body().string();
System.out.println("从服务端返回结果: " + resultData);
}
/**
* 2.使用okhttp调用服务端的GET请求
* 服务端入参注解: @RequestParam
* */
public static void f2() throws Exception {
// 1.请求URL与组装请求参数
String getUrl = "http://127.0.0.1:19091/server/comm/f2";
String obj = "Vue进阶教程";
String para = "?obj=" + URLEncoder.encode(obj, "UTF-8");
getUrl = getUrl + para;
// 2.创建连接与设置连接参数
Request request = new Request.Builder().url(getUrl).build();
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
// 3.发起请求与接收返回值
Response response = okHttpClient.newCall(request).execute();
String resultData = response.body().string();
System.out.println("从服务端返回结果: " + resultData);
}
/**
* 3.使用okhttp调用服务端的GET请求
* 服务端入参注解: @PathVariable
* */
public static void f3() throws Exception {
// 1.请求URL与组装请求参数
String getUrl = "http://127.0.0.1:19091/server/comm/f3/";
String obj = "Vue进阶教程";
obj = URLEncoder.encode(obj, "UTF-8");
getUrl = getUrl + obj;
// 2.创建连接与设置连接参数
Request request = new Request.Builder().url(getUrl).build();
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
// 3.发起请求与接收返回值
Response response = okHttpClient.newCall(request).execute();
String resultData = response.body().string();
System.out.println("从服务端返回结果: " + resultData);
}
}
使用RestTemplate调用http请求
- Jar包位置
RestTemplate,全称org.springframework.web.client.RestTemplate。 本例使用版本。1
2
3
4
5
6dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.3.15</version>
<scope>compile</scope>
</dependency> - 客户端代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62public class Utils05RestTemplateClient {
public static void main(String[] args) throws Exception {
f1();
f2();
f3();
}
/**
* 1.使用RestTemplate调用服务端的POST请求
* 服务端入参注解: @RequestBody
*/
public static void f1() throws Exception {
// 1.请求URL
String postUrl = "http://127.0.0.1:19091/server/comm/f1";
// 2.请求参数JSON格式
Map<String, String> map = new HashMap<>();
map.put("userName", "HangZhou20220718");
map.put("tradeName", "Vue进阶教程");
String json = JSON.toJSONString(map);
// 3.创建RestTemplate
RestTemplate restTemplate = new RestTemplate();
// 4.设置RestTemplate参数(请求头和body)
HttpHeaders headers = new HttpHeaders();
MediaType mediaType = MediaType.parseMediaType("application/json; charset=UTF-8");
headers.setContentType(mediaType);
headers.add("Accept", "application/json");
HttpEntity<String> entity = new HttpEntity<>(json, headers);
// 5.使用RestTemplate发起请求与接收返回值
String resultData = restTemplate.postForObject(postUrl, entity, String.class);
System.out.println("从服务端返回结果: " + resultData);
}
/**
* 2.使用RestTemplate调用服务端的GET请求
* 服务端入参注解: @RequestParam
*/
public static void f2() throws Exception {
// 1.请求URL与组装请求参数
String getUrl = "http://127.0.0.1:19091/server/comm/f2";
String obj = "Vue进阶教程";
String para = "?obj=" + obj;
getUrl = getUrl + para;
// 2.创建RestTemplate
RestTemplate restTemplate = new RestTemplate();
// 3.使用RestTemplate发起请求与接收返回值
String resultData = restTemplate.getForObject(getUrl, String.class);
System.out.println("从服务端返回结果: " + resultData);
}
/**
* 3.使用RestTemplate调用服务端的GET请求
* 服务端入参注解: @PathVariable
*/
public static void f3() throws Exception {
// 1.请求URL与组装请求参数
String getUrl = "http://127.0.0.1:19091/server/comm/f3/";
String obj = "Vue进阶教程";
getUrl = getUrl + obj;
// 2.创建RestTemplate
RestTemplate restTemplate = new RestTemplate();
// 3.使用RestTemplate发起请求与接收返回值
String resultData = restTemplate.getForObject(getUrl, String.class);
System.out.println("从服务端返回结果: " + resultData);
}
}背景色是:orange
结尾。
-
感谢你赐予我前进的力量
赞赏者名单
因为你们的支持让我意识到写文章的价值🙏
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 阜山的博客
评论